#
#  Product controller
#

from dzutil import message
from common.models.user import *
from views.user_view import *
from MySQLdb import IntegrityError

#------------------------------------------------------------------------
class ProductController:

    def _index(self):
        user = Users().current()
        return ShowView(user)

    def _edit(self):
        user = Users().current()
        return EditView(user)

    def _change_password(self):
        return ChangePasswordView(Users().current())

    def _update_password(self,OLD_PASSWORD,NEW_PASSWORD,CONFIRM,save_button=None):
        user = Users().current()
        if not user.authenticate(OLD_PASSWORD):
            message('Invalid old password')
            return ChangePasswordView(user)
        elif not len(NEW_PASSWORD)>=5:
            message('New password too short (min 5 characters)')
            return ChangePasswordView(user)
        elif ' ' in NEW_PASSWORD:
            message('Spaces not allowed in passwords')
            return ChangePasswordView(user)
        elif not NEW_PASSWORD or NEW_PASSWORD <> CONFIRM:
            message('Passwords do not match')
            return ChangePasswordView(user)
        else:
            user.set_password(NEW_PASSWORD)
            user.save()
            message('password changed')
        return ShowView(user)

    def _update(self,**args):
        user = Users().current()
        user.update(args)
        try:
            user.save()
        except IntegrityError:
            message('User loginid exists')
            return EditView(user)
        message('Updated')
        return ShowView(user)

result = ProductController()

